﻿using Fortunate.API.BASE;
using Fortunate.IService;
using Fortunate.Common.Extensions;
using Microsoft.AspNetCore.Mvc;
using Fortunate.ViewModel.FilesModule;
using Fortunate.Application.Entities;
using Fortunate.Common.Global;
using Fortunate.Common.Utility;
using Fortunate.Common.Helper;
using Aliyun.OSS;
using System.Text;
using System.IO;
using NPOI.Util;

namespace Fortunate.API.Controllers
{
    /// <summary>
    /// 文件操作相关
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FilesController : BaseApiController
    {
        /// <summary>
        /// 
        /// </summary>
        protected readonly IFilesTableService _iFilesTableService;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ILoginService _iLoginService;

        /// <summary>
        /// 
        /// </summary>
        public FilesController(IFilesTableService IFilesTableService,
            IWebHostEnvironment webHostEnvironment,
            ILoginService loginService)
        {
            _iFilesTableService = IFilesTableService;
            _webHostEnvironment = webHostEnvironment;
            _iLoginService = loginService;
        }

        /// <summary>
        /// 获取文件数据
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetFilesList([FromQuery] FilesSearch search)
        {
            try
            {
                search.PageIndex = search.PageIndex <= 0 ? 1 : search.PageIndex;
                search.PageCount = search.PageCount <= 0 ? 10 : search.PageCount;
                var data = await _iFilesTableService.GetFilesListAsync(search);
                return Success(data);
            }
            catch (Exception ex)
            {
                return Fail("异常：" + ex.Message);
            }

        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> PostFileUpload(IFormFile file)
        {
            try
            {
                if (file.Length > FortunateGlobalContext.DirectoryConfig.limitSiza)
                {
                    string filecontent = Convert.ToString(((float)file.Length) / 1024 / 1024)[..4];
                    return Fail($"文件大小超出限制（{FortunateGlobalContext.DirectoryConfig.FileMax}）当前 {filecontent} M");
                }
                string code = VerifyCodeHelper.GetCode(5);
                string FilePath = FortunateGlobalContext.DirectoryConfig.GetBusinessAttachmentPath();
                string SaveUrl = string.Concat(_webHostEnvironment.ContentRootPath, FilePath);
                FileContext.SaveBusinessAttachment(file, SaveUrl, code, out string FileType, out string FileName);
                
                FilesTable filesTable = new()
                {
                    id = base.GetGuid,
                    FileDate = Convert.ToDateTime(base.GetDate),
                    FileName = FileName,
                    FilePath = string.Concat(FilePath, FileName),
                    FileType = FileType,
                    FileLength = file.Length,
                    FileRemark = "",
                };
                await _iFilesTableService.InsertFilesTableAsync(filesTable);
                return Success(filesTable.id);
            }
            catch (Exception ex)
            {
                return Fail("异常：" + ex.Message);
            }

        }

        /// <summary>
        /// 删除文件(假删除)
        /// </summary>
        /// <param name="id">文件id</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DeleteFile(string id)
        {
            try
            {
                if (string.IsNullOrEmpty(id)) return Fail("参数错误");
                await _iFilesTableService.DeleteFilesTableAsync(id.ToGuid());
                return Success("删除成功");
            }
            catch (Exception)
            {
                return Fail();
            }

        }

        /// <summary>
        /// 删除文件数据以及文件(物理删除)
        /// </summary>
        /// <param name="id">文件id</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DropFile(string id)
        {
            try
            {
                var filesTable = await _iFilesTableService.GetFilesTableObjectAsync(id.ToGuid());
                if (filesTable == null)
                    return Fail("未找到文件，删除失败");

                string SaveUrl = _webHostEnvironment.ContentRootPath + filesTable.FilePath + "\\" + filesTable.FileName;
                if (Directory.Exists(SaveUrl))
                {
                    System.IO.File.Delete(SaveUrl);
                }
                await _iFilesTableService.DropFilesTableAsync(id.ToGuid());
                return Success("删除成功");
            }
            catch (Exception ex)
            {
                return Fail("异常：" + ex.Message);
            }

        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="id">文件id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> DownloadFile(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Fail("参数错误");
            }
            var filesTable = await _iFilesTableService.GetFilesTableObjectAsync(id.ToGuid());
            //存放路径
            string filePath = _webHostEnvironment.ContentRootPath + filesTable.FilePath + "\\" + filesTable.FileName;
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
            return File(fileStream, "application/octet-stream", filesTable.FileName);
        }
    }
}
